from common.utils.rights import permission_required, view_logging_required
from . import index_bp
from flask import Flask,render_template,request,send_from_directory
import os
from werkzeug.utils import secure_filename
from flask_wtf.form import CombinedMultiDict
from models.form import UploadForm
import time
import numpy as np
import cv2 as cv


@index_bp.get('/turn_pro')
@index_bp.post('/turn_pro')
@view_logging_required
@permission_required("turn:pro")
def turn_pro():
    if request.method == "GET":
        return render_template('admin/cv/turn.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            f = request.files['file']  # 获取文件流
            fileName = secure_filename(f.filename)
            ext = fileName.rsplit('.', 1)[0]  # 获取文件后缀
            unix_time = int(time.time())
            new_filename = str(unix_time) + "." + ext
            upload_path = os.path.curdir + os.path.sep + 'static/' + 'upload/'
            file_url = upload_path + new_filename
            f.save(os.path.join(upload_path, new_filename))
            def myAffine(img):
                height = img.shape[0]
                width = img.shape[1]
                deep = img.shape[2]

            def myFlip(img, direction):
                height = img.shape[0]
                width = img.shape[1]
                deep = img.shape[2]
                imgDst = np.zeros((height, width, deep), np.uint8)
                if direction == 0:
                    for row in range(height):
                        for col in range(width):
                            imgDst[row, width - 1 - col] = img[row, col]
                elif direction == 1:
                    for row in range(height):
                        for col in range(height):
                            imgDst[col, height - 1 - row] = img[row, col]
                elif direction == 2:
                    for row in range(height):
                        for col in range(width):
                            imgDst[height - 1 - row, col] = img[row, col]
                return imgDst
            result = 'static/download/turn.jpg'
            pic = cv.imread(file_url)
            res = myFlip(pic, 0)
            res = np.hstack((pic, res))
            cv.imwrite(result, res)
            return render_template('admin/cv/turn.html', pic=pic, pic_res=result)
        else:
            return "only support jpg,png,gif"

